#!/bin/bash


mkdir -p master master/conf master/data
mkdir -p slave slave/conf slave/data

cat >> master/conf/my.cnf << "EOF"
[mysqld]
server-id = 1 # 主节点的唯一标识
binlog-do-db=testdb  # 指定了要记录二进制日志的数据库
binlog-ignore-db=information_schema,performance_schema # 指定了要忽略的数据库
EOF

cat >> slave/conf/my.cnf << "EOF"
[mysqld]
server-id=2 # 从节点的唯一标识
relay-log=/var/lib/mysql/mysql-relay-bin # 配置中继日志
relay-log-index=/var/lib/mysql/mysql-relay-bin.index  
EOF

cd /root/workspace/ruo-yi_tee/docker-compose
docker-compose -f  masterslave.yml up -d

# sleep 5

# 定义容器名称
MASTER_CONTAINER="mysql-master"
SLAVE_CONTAINER="mysql-slave"

# 等待容器启动的函数
wait_for_container_start_and_mysql_connect () {
    local container_name=$1
    local max_attempts=10
    local attempt=0
    local status

    while [ $attempt -lt $max_attempts ]; do
        status=$(docker inspect -f '{{.State.Running}}' $container_name 2>/dev/null)
        echo $status
        if [ "$status" == "true" ]; then
            # echo 0
            # return 0
            break
        fi
        echo "Waiting for $container_name to start... ($((attempt + 1))/$max_attempts)"
        sleep 2
        attempt=$((attempt + 1))
    done
    if [ "$attempt" -eq $max_attempts ]; then
        echo "Failed to start $container_name within the specified time."
        echo 1
        return 1
    fi
    # 容器启动后，等待能连接到MySQL
    attempt=0
    while [ $attempt -lt $max_attempts ]; do
        result=$(docker exec -it $container_name bash -c "mysql -uroot -p123456 -e \" show databases; \" 2>/dev/null" && echo "success" || echo "fail")
        if [ "$result" == "success" ]; then
            echo "成功连接到 $container_name 内的 MySQL"
            echo 0
            return 0
        fi
        echo "还未连接到 $container_name 内的 MySQL，等待 2 秒后再次尝试..."
        sleep 2
        attempt=$((attempt + 1))
    done
    echo "Failed to connect to MySQL in $container_name within the specified time."
    echo 1
    return 1
}

# 等待主容器启动
result=$(wait_for_container_start_and_mysql_connect $MASTER_CONTAINER)
if [ "$result" -ne 0 ]; then
    exit 1
fi

# 等待从容器启动
result=$(wait_for_container_start_and_mysql_connect $SLAVE_CONTAINER)
if [ "$result" -ne 0  ]; then
    exit 1
fi

# 以下是配置主从复制的相关命令，放在容器都启动成功之后执行

# 进入主节点容器创建用于复制的用户并授权（示例，根据实际情况修改密码等信息）
# docker exec -it $MASTER_CONTAINER bash -c "mysql -uroot -prootpassword -e \" CREATE USER 'replica_user'@'%' IDENTIFIED BY 'replica_password'; GRANT REPLICATION SLAVE ON *.* TO 'replica_user'@'%'; FLUSH PRIVILEGES;\""

# sleep 25
docker exec -it $MASTER_CONTAINER bash -c "mysql -uroot -p123456 -e \" show databases; \" "

docker exec -it $MASTER_CONTAINER bash -c "mysql -uroot -p123456 -e \"show master status;\
CREATE USER 'replica_user'@'%'  IDENTIFIED with mysql_native_password BY '123456';\
GRANT REPLICATION SLAVE ON *.* TO 'replica_user'@'%';\
FLUSH PRIVILEGES;\
SHOW MASTER STATUS \G
\"
"

# 获取主节点二进制日志状态信息
MASTER_LOG_INFO=$(docker exec -it $MASTER_CONTAINER bash -c "mysql -uroot -p123456 -e \"SHOW MASTER STATUS;\"" | grep -E "bin.*[0-9]+")
MASTER_LOG_FILE=$(echo $MASTER_LOG_INFO | awk '{print $2}')
MASTER_LOG_POSITION=$(echo $MASTER_LOG_INFO | awk '{print $4}')

# 进入从节点容器配置主从复制关系（使用获取到的主节点日志信息）
# docker exec -it $SLAVE_CONTAINER bash -c "mysql -uroot -prootpassword -e \"CHANGE MASTER TO MASTER_HOST='$MASTER_CONTAINER', MASTER_USER='replica_user', MASTER_PASSWORD='replica_password', MASTER_LOG_FILE='$MASTER_LOG_FILE', MASTER_LOG_POS=$MASTER_LOG_POSITION; START SLAVE; SHOW SLAVE STATUS \G;\""
docker exec -it $SLAVE_CONTAINER bash -c "mysql -uroot -p123456 -e \" \
 CHANGE MASTER TO \
 MASTER_HOST='$MASTER_CONTAINER', \
 MASTER_USER='replica_user', MASTER_PASSWORD='123456', \
 MASTER_LOG_FILE='$MASTER_LOG_FILE', MASTER_LOG_POS=$MASTER_LOG_POSITION;\
 STOP SLAVE;\
 START SLAVE;\
 SHOW SLAVE STATUS \G \"
 "

 # 确保 Slave_IO_Running 和 Slave_JK_Running 都为 True

# 在主节点容器内登录 MySQL，创建一个测试数据库和表：

################################sql
touch masterslave/master.sql 
cat >> ./masterslave/master.sql << "EOF"
CREATE DATABASE if not exists testdb;
USE testdb;
CREATE TABLE if not exists test_table (
    id INT PRIMARY KEY,
    name VARCHAR(255)
);
INSERT INTO test_table VALUES (1, 'John');
INSERT INTO test_table VALUES (2, 'Alice');
EOF


docker cp /root/workspace/ruo-yi_tee/docker-compose/masterslave/master.sql mysql-master:/opt
docker exec -it mysql-master bash -c "mysql -uroot -p123456 -e 'source /opt/master.sql'"

# 然后在从节点容器内登录 MySQL，查询刚才创建的数据库和表：
# USE testdb;
# SELECT * FROM test_table;

docker exec -it mysql-master bash -c "mysql -uroot -p123456 -e 'show databases; use testdb; show tables;select * from test_table;'" 
# docker exec -it mysql-master bash -c "mysql -uroot -p123456 -e 'delete from testdb.test_table ;'" 
# docker exec -it mysql-master bash -c "mysql -uroot -p123456 -e 'show databases; drop database IF EXISTS testdb; '" 
# docker exec -it mysql-master bash -c "mysql -uroot -p123456 -e 'select * from testdb.test_table'" 
# docker exec -it mysql-slave bash -c "mysql -uroot -p123456 -e ' SHOW SLAVE STATUS \G'" | grep "Slave" 
docker exec -it mysql-slave bash -c "mysql -uroot -p123456 -e 'select * from testdb.test_table;'" 
